package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB1EmailTemplates;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.PcbaCompany;
import com.sailfish.springbootdemo.pojo.db1.PcbaDevice;
import com.sailfish.springbootdemo.pojo.db1.PcbaLine;
import com.sailfish.springbootdemo.pojo.db1.UpkeepHistory;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UpkeepHistoryServiceImpl implements UpkeepHistoryService {

    @Autowired
    private UpkeepHistoryDao upkeepHistoryDao;

    @Autowired
    private OperateService operateService;

    @Autowired
    private CoreAlgorithmService coreAlgorithmService;

    @Autowired
    private PcbaDeviceDao pcbaDeviceDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PcbaLineDao pcbaLineDao;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Autowired
    private PcbaWorkshopDao pcbaWorkshopDao;

    @Autowired
    private PcbaDeviceResourceDao pcbaDeviceResourceDao;

    @Value("${personal.config.env}")
    private String env;

    @Autowired
    private ThirdApiService thirdApiService;

    private String operateSmallType = "保养记录";

    @Override
    public List<UpkeepHistory> getUpkeepHistoryByAssetNumber(String assetNumber, String statusStr, Integer upkeepType, Integer pcbaCompanyId, Integer isCurrent, String searchValue) {
        List<Integer> statusList = new ArrayList<>();
        if (statusStr != null && !"".equals(statusStr)) {
            String[] arr = statusStr.split(",");
            for (String s : arr) {
                statusList.add(Integer.parseInt(s));
            }
        }
        List<UpkeepHistory> list = upkeepHistoryDao.getUpkeepHistoryByAssetNumber(assetNumber, statusList, upkeepType, pcbaCompanyId, isCurrent, searchValue);
        for (UpkeepHistory upkeepHistory : list) {
            PcbaDevice byAssetNumber = pcbaDeviceDao.getByAssetNumber(upkeepHistory.getAssetNumber());
            if (upkeepHistory.getOwnerId() != null && !"".equals(upkeepHistory.getOwnerId().toString())) {
                upkeepHistory.setOwner(userDao.getUserInfoById(upkeepHistory.getOwnerId()));
            }
            if (byAssetNumber.getPcbaLineId() != null && !"".equals(byAssetNumber.getPcbaLineId().toString())) {
                PcbaLine pcbaLineById = pcbaLineDao.getPcbaLineById(byAssetNumber.getPcbaLineId());
                if (pcbaLineById != null) {
                    Integer pCompanyId = pcbaLineById.getPcbaCompanyId();
                    Integer pWorkshopId = pcbaLineById.getPcbaWorkshopId();
                    pcbaLineById.setPcbaCompany(pcbaCompanyDao.getPcbaCompanyById(pCompanyId));
                    pcbaLineById.setPcbaWorkshop(pcbaWorkshopDao.getPcbaWorkshopById(pWorkshopId));
                }
                byAssetNumber.setPcbaLine(pcbaLineById);
            }
            upkeepHistory.setPcbaDevice(byAssetNumber);
        }
        return list;
    }

    @Override
    public Result updateUpkeepHistory(UpkeepHistory upkeepHistory) {
        try {
            if (upkeepHistory == null) {
                return ResultUtil.error(500, "缺少参数upkeepHistory", "Miss Param upkeepHistory", null);
            }
            if (upkeepHistory.getUpkeepHistoryId() == null || "".equals(upkeepHistory.getUpkeepHistoryId().toString())) {
                return ResultUtil.error(500, "缺少参数upkeepHistoryId", "Miss Param upkeepHistoryId", null);
            }
            String userId = UserHeaderHolder.getUserId();

            UpkeepHistory oldUpkeepHistory = upkeepHistoryDao.getUpkeepHistoryById(upkeepHistory.getUpkeepHistoryId());

            upkeepHistory.setUpdateTime(new Date());
            upkeepHistory.setOwnerId(Integer.parseInt(userId));
            upkeepHistory.setSubmitter(Integer.parseInt(userId));
            Integer integer = upkeepHistoryDao.updateUpkeepHistoryById(upkeepHistory);
            if (integer > 0) {

                // 操作记录
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldUpkeepHistory), JSONObject.toJSONString(upkeepHistory)));

                upkeepHistory = upkeepHistoryDao.getUpkeepHistoryById(upkeepHistory.getUpkeepHistoryId());

                String assetNumber = upkeepHistory.getAssetNumber();
                PcbaDevice byAssetNumber = null;
                if (assetNumber != null && !"".equals(assetNumber)) {
                    byAssetNumber = pcbaDeviceDao.getByAssetNumber(assetNumber);
                }
                if (upkeepHistory.getStatus() == 1) {
                    // 完成保养
                    if (byAssetNumber != null) {
                        coreAlgorithmService.refreshDeviceUpkeepStatus(byAssetNumber.getPcbaDeviceId());
                    }
                }

                // 发送邮件通知
                try {
                    List<User> userList = new ArrayList<>();
                    if (byAssetNumber != null) {
                        PcbaLine pcbaLine = pcbaLineDao.getPcbaLineById(byAssetNumber.getPcbaLineId());
                        if (pcbaLine != null) {
                            PcbaCompany pcbaCompany = pcbaCompanyDao.getPcbaCompanyById(pcbaLine.getPcbaCompanyId());
                            if (pcbaCompany != null) {
                                String emailOwners3 = pcbaCompany.getEmailOwners3();
                                if (emailOwners3 != null && !"".equals(emailOwners3)) {
                                    String[] split = emailOwners3.split(",");
                                    for (String s : split) {
                                        if (s.contains("/")) {
                                            String[] strings = s.split("\\/");
                                            if (strings.length == 2) {
                                                String domainAccount = strings[1];
                                                if (domainAccount != null && !"".equals(domainAccount)) {
                                                    User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                                    if (u != null) {
                                                        userList.add(u);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    List<MailAddress> mailAddressList = new ArrayList<>();
                    for (User user : userList) {
                        if(user.getEmail().contains(",")){
                            String[] emailsArr = user.getEmail().split(",");
                            for (String email : emailsArr) {
                                MailAddress mailAddress = new MailAddress();
                                mailAddress.setMailAddress(email);
                                mailAddress.setType(0);
                                mailAddressList.add(mailAddress);
                            }
                        }else{
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(user.getEmail());
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }
                    if (mailAddressList.size() > 0) {
                        if (upkeepHistory.getStatus() == 1) {
                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_UPKEEP_HISTORY_TITLE_OK, DB1EmailTemplates.DEVICE_UPKEEP_HISTORY_MAIL_CONTENT_TITLE_OK,
                                    DB1EmailTemplates.DEVICE_UPKEEP_HISTORY_MAIL_CONTENT_OK, "10086", mailAddressList, null, null, null, null, 2, null);
                            if (result.getCode() == 200) {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("设备维护保养计划审核结果邮件,发送成功");
                            } else {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("设备维护保养计划审核结果邮件,发送失败:" + result.getMsgCn());
                            }
                        } else if (upkeepHistory.getStatus() == 2) {
                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_UPKEEP_HISTORY_TITLE_NO, DB1EmailTemplates.DEVICE_UPKEEP_HISTORY_MAIL_CONTENT_TITLE_NO,
                                    DB1EmailTemplates.DEVICE_UPKEEP_HISTORY_MAIL_CONTENT_NO, "10086", mailAddressList, null, null, null, null, 2, null);
                            if (result.getCode() == 200) {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("设备维护保养计划审核结果邮件,发送成功");
                            } else {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("设备维护保养计划审核结果邮件,发送失败:" + result.getMsgCn());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                    System.out.println("设备维护保养结果审核结果邮件发送失败");
                }

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
